<?php
/**
 * 产品销量公共模型
 * @author shipanpan
 *
 */
class Application_Model_ProductSales extends Model_Base {
	const SEVEN_DAY = 7; //前7天
	const THE_SECOND_WEEK = '8-14'; //前第二周
	const FIFTEEN_DAY = 15; //前15天
	const THIRTY_DAY = 30; //前30天

	const SALES_TYPE = [
		self::SEVEN_DAY => 1,
		self::FIFTEEN_DAY => 2,
		self::THIRTY_DAY => 3,
		self::THE_SECOND_WEEK => 5,
	];

	public function __construct() {
		$this->db = $this->db();
	}

	  /**
		* 获取一条销量统计记录
	    * @param  [type] $goodsSn       sku
	    * @param  [type] $warehouseCode 仓库代码
	   * */
	 public function getOne(){
	        $where = $this->db->quoteInto("goods_sn=?", $goodsSn);
			$where .= " AND " . $this->db->quoteInto("warehouse_code=?", $warehouseCode);
			return $this->db->fetchRow("select * from p_product_sales_statistics where $where");
	}

	/**
	 * 某一个产品在某一个仓库某一时间段内的备货销售数量(备货销量的含义是：去除实际销量中的最大值后的平均值)
	 * @param  [type] $goodsSn       sku
	 * @param  [type] $warehouseCode 仓库代码
	 * @param  [type] $days          获取前多天销量；
	 * @return [type]                [description]
	 */
	public function goodsBackupSalesQuantity($goodsSn, $warehouseCode,$days) {
		$salesQuantityInfo = $this->getOne($goodsSn, $warehouseCode);
	    if(!$salesQuantityInfo){
			return 0;
		}
		$fieldName=[
			self::SEVEN_DAY => 'sale_7',
			self::FIFTEEN_DAY => 'sale_15',
			self::THIRTY_DAY => 'sale_30',
			self::THE_SECOND_WEEK => 'sale_second_week',
		];
		if(!isset($fieldName[$days])){
			return $this->_error("未知的销量统计天数：".$days);
		}
		return $salesQuantityInfo[$fieldName[$days]];
	}

	/**
	 * 某一个产品在某一个仓库某一时间段内的实际销售数量
	 * @param  [type] $goodsSn       sku
	 * @param  [type] $warehouseCode 仓库代码
	 * @param  [type] $days          获取前多天销量；
	 * @return [type]                [description]
	 */
	public function goodsRealSalesQuantity($goodsSn, $warehouseCode,$days) {
		$salesQuantityInfo = $this->getOne($goodsSn, $warehouseCode);
		if(!$salesQuantityInfo){
			return 0;
		}
		$fieldName=[
			self::SEVEN_DAY => 'real_sale_7',
			self::FIFTEEN_DAY => 'real_sale_15',
			self::THIRTY_DAY => 'real_sale_30',
			self::THE_SECOND_WEEK => 'real_second_week',
		];
		if(!isset($fieldName[$days])){
			return $this->_error("未知的销量统计天数：".$days);
		}
		return $salesQuantityInfo[$fieldName[$days]];
	}

	/**
	 * 获取销量类别名称
	 * @param  int $days 销量类别
	 * @return string
	 */
	public static function daysName($days) {
		$name = [self::SEVEN_DAY => '前七天', self::FIFTEEN_DAY => '前15天', self::THIRTY_DAY => '前30天'];
		return $name[$days] ?? '';
	}
}